package ext.tianma.workflow;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import wt.util.WTException;
import ext.tianma.util.PropertiesUtil;

public class sendToRDPForWorkItem {
	private static DefaultHttpClient client;

	private static String urls = "http://common-tmrdp-sit.apps-dev.tianma.cn";
	// private static String urls = "http://10.100.48.178:8882";
	// private static String key = "Authorization";
	// private static String value
	// ="{\"key\":\"Authrization\",\"userId\":\"025CE39B20EA11E7A81AC85B767C89C1\",\"userName\":\"admin\",\"token\":\"##TIQUYWOOEWEPE$$\",\"timestamp\":1540277255720,\"credentials\":\"##TIQUYWOOEWEPE$$\"}";
	private static String key = "Cookie";
	private static String value = "JSESSIONID=42f8b70e-9aaa-4d03-b19c-1444b1df83e4; Authorization=%7B%22key%22%3A%22Authrization%22%2C%22userId%22%3A%22025CE39B20EA11E7A81AC85B767C89C1%22%2C%22userName%22%3A%22admin%22%2C%22token%22%3A%22%23%23TIQUYWOOEWEPE%24%24%22%2C%22timestamp%22%3A1541640560408%2C%22credentials%22%3A%22%23%23TIQUYWOOEWEPE%24%24%22%2C%22principal%22%3A%22025CE39B20EA11E7A81AC85B767C89C1%22%7D; Hm_lpvt_0a3967d918b12205a0260d6fbc9abf6e=1541640459; authSysRoles=%5B%22101%22%2C%2203ccdbb4995640faaf0966c4a89dd362%22%2C%2262b85f8a2a004dd1bdf37aa5d204be25%22%2C%22062c6e1c43c64c8281fc6e22c31c90c8%22%5D";

	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	/***
	 * 任務代辦
	 * 
	 * @param processName
	 * @param username
	 * @param msg
	 * @param activityname
	 * @param url
	 * @param processId
	 * @param contentUrl
	 * @param startUserId
	 * @param source
	 * @param tenantId
	 * @param dateTime
	 * @param workItemId
	 * @param processState
	 * @param workItemStatus
	 * @param ownerID
	 * @param pboName
	 * @return
	 * @throws WTException
	 * @throws JSONException
	 */
	public static String sendWorkItemToRDP(String processName, String username, String msg, String activityname,
			String url, String processId, String contentUrl, String startUserId, String source, String tenantId,
			String dateTime, String workItemId, String processState, String workItemStatus, String ownerID,
			String pboName) throws JSONException {
		JSONObject jsonObject = createJSONObject(processName, username, msg, activityname, url, processId, contentUrl,
				startUserId, source, tenantId, dateTime, workItemId, processState, workItemStatus, ownerID, pboName);
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrlHost = ut.getValueByKey("erdp.url");
		String cookieKey = ut.getValueByKey("erdp.key");
		//String cookieValue = ut.getValueByKey("erdp.value");
		String cookieValue = getRDPToken();
		String erdpurl = erdpUrlHost + "/workflow/thirdparty/createTask";
		System.out.println("erdpurl====>>>" + erdpurl);
		System.out.println("jsonObject====>>>" + jsonObject);
		String returnMeg = "";
		try {
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			HttpPost httpPost = new HttpPost(erdpurl);
			httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8");
			httpPost.addHeader("appId", "erdp");
			httpPost.setHeader(cookieKey, cookieValue);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("taskjson", jsonObject.toJSONString()));
			UrlEncodedFormEntity he = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
			httpPost.setEntity(he);
			HttpResponse response;
			response = httpClient.execute(httpPost);

			if ("200".equals(response.getStatusLine().getStatusCode())) {
				HttpEntity entityRep = response.getEntity();
				System.out.println("entityRep===>>>" + entityRep.toString());
				String strrep = "";
				if (entityRep != null) {
					strrep = EntityUtils.toString(response.getEntity());
					httpPost.abort();
				}
				System.out.println("strrep===========>>>" + strrep);
				// 返回
				if (strrep != null && !"".equals(strrep)) {
					System.out.println("==00==");
					JSONObject obj = new JSONObject(strrep);
					if (obj.has("success")) {
						boolean flag = obj.getBoolean("success");
//						System.out.println("obj.getString(\"res\")===>>>" + obj.getString("res"));
						if (flag) {
							System.out.println("send sucess====>>>");
							// if(!"".equals(obj.getString("res"))&&obj.getString("res")!=null) {
							// JSONObject obj2 = new JSONObject(obj.getString("res"));
							// returnMeg = obj2.toString();
							// System.out.println("obj2====>>>" + returnMeg);
							// }
							// return returnMeg;
						}
					}
				}
			}else {
				HttpEntity entityRep = response.getEntity();
				System.out.println("entityRep===>>>" + entityRep.toString());
				if (entityRep != null) {
					String strrep = "";
					strrep = EntityUtils.toString(response.getEntity());
					httpPost.abort();
					System.out.println("strrep===========>>>" + strrep);
				}
				
			}
		} catch (UnsupportedEncodingException e1) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e1.printStackTrace();
		} catch (ClientProtocolException e) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (IOException e) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}

		return returnMeg;

	}

	/***
	 * 创建第三方历史任务（完成任务调用）POST请求
	 * 
	 * @param taskId
	 * @param source
	 * @param procInstId
	 * @param isEnd
	 * @return
	 * @throws WTException
	 * @throws JSONException
	 */
	public static String sendWorkItemToRDPForPost(String taskId, String source, String procInstId, boolean isEnd)
			throws WTException, JSONException {

		JSONObject jsonObject = createJSONObjects(taskId, source, procInstId, isEnd);
		String strUrl = "http://common-tmrdp-sit.apps-dev.tianma.cn";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrlHost = ut.getValueByKey("erdp.url");
		String cookieKey = ut.getValueByKey("erdp.key");
		//String cookieValue = ut.getValueByKey("erdp.value");
		String cookieValue = getRDPToken();
		String erdpurl = erdpUrlHost + "/workflow/thirdparty/createHistoryTask";
		System.out.println("jsonObject====>>>" + jsonObject);
		System.out.println("erdpurl=======>>>" + erdpurl);
		String returnMeg = "";
		try {
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			HttpPost httpPost = new HttpPost(erdpurl);
			httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8");
			httpPost.addHeader("appId", "erdp");
			httpPost.setHeader(cookieKey, cookieValue);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("taskId", taskId));
			nvps.add(new BasicNameValuePair("source", source));
			nvps.add(new BasicNameValuePair("procInstId", procInstId));
			nvps.add(new BasicNameValuePair("isEnd", "false"));
			UrlEncodedFormEntity he = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
			httpPost.setEntity(he);
			HttpResponse response;
			response = httpClient.execute(httpPost);
			HttpEntity entityRep = response.getEntity();
			System.out.println("entityRep==>>" + entityRep);
			if ("200".equals(response.getStatusLine().getStatusCode())) {
				String strrep = "";
				if (entityRep != null) {
					System.out.println("into ==>>");
					strrep = EntityUtils.toString(response.getEntity());
					httpPost.abort();
				}
				System.out.println("strrep===========>>>" + strrep);
				// 返回
				if (strrep != null && !"".equals(strrep)) {
					JSONObject obj = new JSONObject(strrep);
					if (obj.has("success")) {
						boolean flag = obj.getBoolean("success");
						if (flag) {
							// if(!"".equals(obj.getString("res"))) {
							// JSONObject obj2 = new JSONObject(obj.getString("res"));
							// returnMeg = obj2.toString();
							// }
						}
					}
				}
			}else {
				System.out.println("entityRep===>>>" + entityRep.toString());
				if (entityRep != null) {
					String strrep = "";
					strrep = EntityUtils.toString(response.getEntity());
					httpPost.abort();
					System.out.println("strrep===========>>>" + strrep);
				}
				
			}
		} catch (UnsupportedEncodingException e1) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e1.printStackTrace();
		} catch (ClientProtocolException e) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (IOException e) {
			return "接口异常";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}

		return returnMeg;

	}

	/***
	 * 通过流程id删除，批量用分;号分割（Delete请求）
	 * 
	 * @param processInstanceIds
	 *            source
	 * @return
	 * @throws WTException
	 */
	public static String sendWorkItemToRDP(String processInstanceIds, String source) {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrlHost = ut.getValueByKey("erdp.url");
		String erdpurl = erdpUrlHost + "/workflow/thirdparty/process/" + processInstanceIds + "/"
				+ source;
		System.out.println("erdpurl===>>" + erdpurl);
		String returnstr = "";
		try {

			// { success: true, code: "200", message: "", res: {} }
			returnstr = sendXMLDataByPOST(erdpurl);
			System.out.println(returnstr);
			JSONObject obj;
			try {
				if (returnstr != null && !"".equals(returnstr)) {
					obj = new JSONObject(returnstr);
					if (obj.has("success")) {
						boolean flag = obj.getBoolean("success");
						// if (flag) {
						// if(!"".equals(obj.getString("res"))) {
						// JSONObject obj2 = new JSONObject(obj.getString("res"));
						// returnstr = obj2.toString();
						//
						// System.out.println("obj2======>>>" + obj2.toString());
						// }
						// return returnstr;
						// }
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (ClientProtocolException e) {
			return "接口异常";
			// e.printStackTrace();
		} catch (IOException e) {
			// e.printStackTrace();
			return "接口异常";
		}catch (IllegalStateException s) {
			System.out.println("====>>><<<===");
			return "接口异常";
		}
		return returnstr;

	}

	/**
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String sendXMLDataByPOST(String url) throws ClientProtocolException, IOException {
		try {
			if (client == null) {
				client = new DefaultHttpClient();
				enableSSL(client);
			}
			PropertiesUtil ut = new PropertiesUtil(configFilePath);
			String cookieKey = ut.getValueByKey("cookie.key");
			String cookieValue = ut.getValueByKey("cookie.value");
			client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

			HttpDelete delete = new HttpDelete(URLDecoder.decode(url));
			delete.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			delete.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			delete.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			delete.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
			delete.setHeader(cookieKey, cookieValue);
			HttpResponse response = client.execute(delete);
			HttpEntity entityRep = response.getEntity();
			String strrep = "";
			if ("200".equals(response.getStatusLine().getStatusCode())) {
				if (entityRep != null) {
					strrep = EntityUtils.toString(response.getEntity());
					delete.abort();
				}
			}
			return strrep;
		} finally {
			//关闭流
			if (client != null) {
				client.getConnectionManager().shutdown();
			}
			
		}
		
	}

	/**
	 * 
	 * @param xml
	 * @return
	 */
	public static String getUTF8XMLString(String xml) {
		StringBuffer sb = new StringBuffer();
		sb.append(xml);
		String xmString = "";
		try {
			xmString = URLEncoder.encode(sb.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		return xmString.toString();
	}

	/**
	 * 访问https的网站
	 * 
	 * @param httpclient
	 */
	private static void enableSSL(DefaultHttpClient httpclient) {
		// 调用ssl
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpclient.getConnectionManager().getSchemeRegistry().register(https);
		} catch (Exception e) {
		}
	}

	// 创建JSONObject对象
	/***
	 * String processName = ""; String username = ""; String msg = ""; String
	 * activityname = ""; String url = ""; String processId = ""; String contentUrl
	 * = ""; String startUserId = ""; String source = "PLM"; String tenantId = "2";
	 * String dateTime = ""; String workItemId = ""; String processState = "";
	 * String workItemStatus = ""; String ownerID = "";
	 * 
	 * 
	 * 
	 * 
	 * "taskjson:{ taskId: ""768347HGGF8"", //任务id processName: ""部件升级颜色流程"", //流程名称
	 * businessName: ""部件升级颜色流程"", //业务流程名称 businessState: ""审核中"", //PBo业务状态 url:
	 * ""http://baidu.com"", // 流程审批链接 processUrl:""流程查看页面的url""， //流程页面的超链接 source:
	 * ""PLM"", //来源 tenantId: ""2"",//模块id （可以自己定义key值） suspensionState: ""1"", //
	 * 是否挂起 1否 0是 priority: ""50"", //优先级(50低，100中，150高) startUserId: ""系统登录账号"",
	 * //流程启动人 工号 assignee: ""系统登录账号"", //任务处理人 owner: ""系统登录账号"", //任务所属人
	 * description: ""变更中"", //描述 name: ""变更中"", // 节点名称 executionId: ""567"",
	 * //任务执行id procInstId: ""789"", //流程实例id wfprocessID taskDefKey: ""change"",
	 * //任务定义key procDefId: ""1234"", // 流程定义id dueDate: ""2018-10-31"" //到期时间 已分配时间
	 * }"
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * @return
	 * @throws JSONException
	 */
	private static JSONObject createJSONObject(String processName, String username, String msg, String activityname,
			String url, String processId, String contentUrl, String startUserId, String source, String tenantId,
			String dateTime, String workItemId, String processState, String workItemStatus, String ownerID,
			String pboName) throws JSONException {
		System.out.println("ownerID===>>" + ownerID);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("taskId", workItemId);
		jsonObject.put("processName", processName);
		jsonObject.put("businessName", pboName);
		jsonObject.put("businessState", "审核中");
		jsonObject.put("url", url);
		jsonObject.put("processUrl", contentUrl);
		jsonObject.put("source", "PLM");
		jsonObject.put("tenantId", "2");
		//项目二期新增category 类型---根据元tenantId传参而定 3：issue 2: task 8: project 4: risk
		//无影响,所以写死,不动态传参,后面有需要在改动态
		jsonObject.put("category", "task");
		jsonObject.put("suspensionState", "");
		jsonObject.put("priority", "20");
		jsonObject.put("startUserId", startUserId);
		jsonObject.put("assignee", ownerID);
		jsonObject.put("owner", ownerID);
		jsonObject.put("description", "");
		jsonObject.put("name", activityname);
		jsonObject.put("executionId", workItemId);
		jsonObject.put("procInstId", processId);
		jsonObject.put("taskDefKey", "");
		jsonObject.put("procDefId", "");
		jsonObject.put("dueDate", "");

		return jsonObject;
	}

	private static JSONObject createJSONObjects(String processId, String source, String workItemId, boolean isEnd)
			throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("taskId", workItemId);
		jsonObject.put("source", "PLM");
		jsonObject.put("tenantId", "2");
		jsonObject.put("procInstId", processId);
		jsonObject.put("isEnd", isEnd);

		return jsonObject;
	}

	/**
	 * 重写验证方法，取消检测ssl
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {
		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};

	public static void main(String[] args) throws JSONException {
		// try {
		System.out.println("===11===");
		//String token = getRDPToken();
		//System.out.println("token:"+token);
		sendWorkItemToRDP("乱码测试", "admin", "乱码测试", "乱码测试", "乱码测试", "1212", "1122", "1122", "1122", "1122", "1122",
				"1122", "1122", "1212", "admin", "1212");
		System.out.println("===11===");
		// String str = sendWorkItemToRDPForPost("11","11","11",false);
		// System.out.println("=====>>"+str);
		// } catch (WTException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}
	/**
	 * 获取RDP的token
	 * @return
	 * @throws JSONException 
	 */
	public static String getRDPToken() throws JSONException {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrlHost = ut.getValueByKey("erdp.url");
		String tokenUsername = ut.getValueByKey("erdp.tokenUsername");
		String tokenPassword = ut.getValueByKey("erdp.tokenPassword");
		String erdpurl = erdpUrlHost +"/tmrdp/v1/auth/token";
		String token="";
		// 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpPost对象
        HttpPost post = new HttpPost(erdpurl);
        // 3. 设置POST请求传递参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", tokenUsername));
        params.add(new BasicNameValuePair("password", tokenPassword));
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 4. 执行请求并处理响应
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null){
            	String strrep = EntityUtils.toString(response.getEntity());
				if (strrep != null && !"".equals(strrep)) {
					JSONObject obj = new JSONObject(strrep);
					if (obj.has("access_token")) {
						String access_token = obj.getString("access_token");
						if(access_token != null && !"".equals(access_token)) {
							token = "Bearer "+access_token;
						}
					}
				}
            	
            }
            response.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return token;
	}

}
